package org.csu.mypetstoreback.service;

import org.csu.mypetstoreback.domain.Manager;
import org.csu.mypetstoreback.persistence.ManagerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Service
public class ManagerService extends Throwable {
    @Autowired
    private ManagerMapper managerMapper;

    public Manager getManager(String username){
        return managerMapper.getManagerByUsername(username);
    }

    public Manager getManager(String username, String password){
        Manager manager = new Manager();
        manager.setUsername(username);
        manager.setPassword(password);
        return managerMapper.getManagerByUsernameAndPassword(manager);
    }
    public Manager getManagerByPhone(String phone){
        return managerMapper.getManagerByPhone(phone);
    }

    public void insertManager(Manager manager) {
//        name,entryTime,address,birthDay,sex设置默认值
        manager.setName("Please set true name.");
        manager.setAddress("Please set address.");
        manager.setBirthDay("Please set birthday.");
        managerMapper.insertManager(manager);
    }

    public void updateManager(Manager manager){
        managerMapper.updateManager(manager);
    }

    public String findPassWord(String email) throws MessagingException {
        String  authcode=managerMapper.findPassword(email);
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
        properties.setProperty("mail.smtp.auth", "true");//需要验证
        properties.setProperty("mail.debug", "true");//设置debug模式 后台输出邮件发送的过程
        Session session = Session.getInstance(properties);
        session.setDebug(true);//debug模式
        System.out.println(email+"1"+authcode);
        //邮件信息
        Message messgae = new MimeMessage(session);
        messgae.setFrom(new InternetAddress("1360230995@qq.com"));//设置发送人
        messgae.setText("YOUR PASSWORD IS:" + authcode + ". THANK YOU FOUR USING OUR WEBSITE!");//设置邮件内容
        messgae.setSubject("Mail Authentication");//设置邮件主题
        //发送邮件
        Transport tran = session.getTransport();
        tran.connect("smtp.qq.com",587, "1360230995@qq.com", "zqabgkgsbaeafgaj");//连接到QQ邮箱服务器
        tran.sendMessage(messgae, new Address[]{ new InternetAddress(email)});//设置邮件接收人
        tran.close();
        return authcode;
    }
}
